package com.jxl_dyw.UI;

import com.jxl_dyw.entity.Dept;
import com.jxl_dyw.entity.Employee;
import com.jxl_dyw.hashMap.MyHashMap;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;

/**
 * 部门类型的UI界面
 */
public class DeptUI extends JPanel {
    private JTable departmentTable;
    private static DefaultTableModel tableModel;
    // 部门信息文件路径
    static String filePath = "src/main/resources/Dept.csv";
    private static MyHashMap<String, Dept> deptMap=new MyHashMap<>();

    public static MyHashMap<String, Dept> getDeptMap() {
        return deptMap;
    }

    public DeptUI() throws IOException {
        setLayout(new BorderLayout());
        // 从文件中读取部门数据
        readDeptFromFile(filePath);
        // 创建表格模型
        String[] columnNames = {"ID", "部门名称", "负责人", "成立日期"};
        tableModel = new DefaultTableModel(columnNames, 0); // 初始化为空表格

        // 读取哈希表的数据，并将对象中的数据添加到表格中
        for (Dept dept : deptMap.values()) {
            Object[] rowData = {
                    dept.getDeptId(),
                    dept.getDeptName(),
                    dept.getBuildPeople(),
                    dept.getBuildTime()
            };
            tableModel.addRow(rowData); // 将每一行数据添加到表格模型中
        }

        // 创建表格
        departmentTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(departmentTable);
        add(scrollPane, BorderLayout.CENTER);

        // 创建顶部栏
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

        // 查询按钮
        JButton checkButton = new JButton("查询部门");
        // 搜索框
        JTextField searchField = new JTextField(20);
        JButton addButton = new JButton("新增部门");
        //排序下拉列表框
        JComboBox<String> comboBox = new JComboBox<>();
        comboBox.addItem("默认");
        comboBox.addItem("部门名称a->z升序");
        comboBox.addItem("部门名称z->a降序");


        topPanel.add(checkButton);
        topPanel.add(searchField);
        topPanel.add(addButton);
        topPanel.add(comboBox);

        add(topPanel, BorderLayout.NORTH);

        // 调整表格的行高
        for (int row = 0; row < departmentTable.getRowCount(); row++) {
            departmentTable.setRowHeight(30); // 调整行高以适应按钮
            //设置表格的字体
            departmentTable.setFont(new Font("宋体", Font.PLAIN, 14));
        }
        addButton.addActionListener(e -> {
            AddDeptUI addDeptUI = new AddDeptUI();
        });

        //为下拉框的选项添加事件监听器
        comboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Object selected = comboBox.getSelectedItem();
                if (selected.equals("部门名称a->z升序")) {
                    //按姓名a->z升序
                    Object[] sortAsc = deptMap.sortByNameAsc(deptMap);
                    String[] stringSortAsc = Arrays.copyOf(sortAsc, sortAsc.length, String[].class);
                    refreshTablesort(stringSortAsc);

                    //刷新表格

                } else if (selected.equals("部门名称z->a降序")) {
                    //按姓名z->a降序
                    Object[] sortDesc = deptMap.sortByNameDesc(deptMap);
                    String[] stringSortDesc = Arrays.copyOf(sortDesc, sortDesc.length, String[].class);
                    refreshTablesort(stringSortDesc);

                    //刷新表格

                }else {
                    refreshTable();
                }
            }
        });

        // 为查询按钮添加事件监听器
        checkButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String searchName = searchField.getText().trim();

                // 清空表格
                tableModel.setRowCount(0);

                if (searchName.isEmpty()) {
                    refreshTable();
                } else {
                    boolean found = false;
                    for (Dept dept : deptMap.values()) {
                        if (dept.getDeptName().contains(searchName)) {
                            Object[] rowData = {
                                    dept.getDeptId(),
                                    dept.getDeptName(),
                                    dept.getBuildPeople(),
                                    dept.getBuildTime()
                            };
                            tableModel.addRow(rowData);
                            found = true;
                        }
                    }
                    if (!found) {
                        JOptionPane.showMessageDialog(DeptUI.this, "未找到匹配的部门", "查询结果", JOptionPane.WARNING_MESSAGE);
                    }
                }
            }
        });
       // 添加鼠标右键菜单
        departmentTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    int row = departmentTable.rowAtPoint(e.getPoint());
                    if (row >= 0) {
                        showPopupMenu(e, row);
                    }
                }
            }
        });
    }

    // 刷新排序后的表格
    private void refreshTablesort(String []keys) {
        // 清空表格
        tableModel.setRowCount(0);

        // 遍历哈希表，将每个员工的信息添加到表格中
        for (String key: keys) {
            Object[] rowData = {
                    deptMap.get(key).getDeptId(),
                    deptMap.get(key).getDeptName(),
                    deptMap.get(key).getBuildPeople(),
                    deptMap.get(key).getBuildTime()
            };
            tableModel.addRow(rowData); // 将每一行数据添加到表格模型中
        }
    }

    // 显示鼠标右键菜单
    private void showPopupMenu(MouseEvent e, int row) {
        JPopupMenu popupMenu = new JPopupMenu();

        JMenuItem editItem = new JMenuItem("编辑");
        editItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 获取选中的行数据
                String deptName = (String) tableModel.getValueAt(row, 1);
                Dept dept = deptMap.get(deptName);

                // 弹出编辑窗口
                new EditDeptUI(dept);
            }
        });
        popupMenu.add(editItem);

        JMenuItem deleteItem = new JMenuItem("删除");
        deleteItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 获取选中的行数据
                String deptName = (String) tableModel.getValueAt(row, 1);
                Dept dept = deptMap.get(deptName);

                // 弹出确认对话框
                int confirm = JOptionPane.showConfirmDialog(DeptUI.this, "确定要删除部门 " + dept.getDeptName() + " 吗？", "确认删除", JOptionPane.YES_NO_OPTION);
                //如果该部门下有员工，则不能删除
                if (hasEmployee(deptName)) {
                    JOptionPane.showMessageDialog(DeptUI.this, "该部门下有员工，不能删除", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                if (confirm == JOptionPane.YES_OPTION) {
                    // 删除部门
                    deptMap.remove(deptName);
                    tableModel.removeRow(row);

                    // 将新的数据写入文件中
                    try {
                        writeDeptToFile(filePath);
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(DeptUI.this, "保存部门信息失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });
        popupMenu.add(deleteItem);

        popupMenu.show(e.getComponent(), e.getX(), e.getY());
    }

    //判断该部门是否有员工
    public static boolean hasEmployee(String deptName) {
        for (Employee emp : EmpUI.getEmployeeMap().values()) {
            if (emp.getPosition().equals(deptName)) {
                return true;
            }
        }
        return false;
    }

    //将哈希表中的数据写入到CSV文件中
    public static void writeDeptToFile(String filePath) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {

            // 遍历哈希表，将每个员工的信息写入CSV文件
            for (Dept dept : deptMap.values()) {
                writer.write(String.join(",",
                        dept.getDeptId(),
                        dept.getDeptName(),
                        dept.getBuildPeople(),
                        dept.getBuildTime()
                ));
                writer.newLine();
            }
        }
    }


    // 刷新表格，重新加载哈希表中的数据
    public static void refreshTable() {
        loadDeptDataToTable();
    }


    // 从哈希表中加载员工数据到表格
    private static void loadDeptDataToTable() {
        // 清空表格
        tableModel.setRowCount(0);

        // 遍历哈希表，将每个员工的信息添加到表格中
        for (Dept dept : deptMap.values()) {
            Object[] rowData = {
                    dept.getDeptId(),
                    dept.getDeptName(),
                    dept.getBuildPeople(),
                    dept.getBuildTime()
            };
            tableModel.addRow(rowData); // 将每一行数据添加到表格模型中
        }
    }

    // 读取 CSV 文件并将数据添加到 employeeMap 中
    public void readDeptFromFile(String filePath) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 按逗号分隔每一行
                String[] fields = line.split(",");

                // 创建 Employee 对象
                Dept dept = new Dept(
                        fields[0],
                        fields[1],
                        fields[2],
                        fields[3]
                );

                // 将 dept对象添加到哈希表中，以部门的名字作为键
                deptMap.put(dept.getDeptName(), dept);
            }
        }
    }
}